package com.nononsenseapps.feeder.processor.interceptor

import com.nononsenseapps.feeder.core.R
import com.nononsenseapps.feeder.db.entity.FeedItem
import com.nononsenseapps.feeder.processor.Interceptor
import com.nononsenseapps.feeder.util.*

class UnfoldInterceptor: Interceptor {
    override fun intercept(chain: Interceptor.Chain): FeedItem {
        val feed=chain.getFeed()
        val feedItem=chain.getFeedItem()
        val context=chain.getProcessContext()

        val description=feedItem.description

        feedItem.image_count = imageCount(description) ?:0

        if(feedItem.image_count > 0) context.modifyFlag=true

        if(feedItem.imageUrl.isNullOrEmpty() && feedItem.image_count>0) {
            feedItem.imageUrl = thumbnail(description, null)
            context.modifyFlag=true
        }

        if(feedItem.plainSnippet.isEmpty() || chain.getProcessContext().context.getString(R.string.full_page_loading) == feedItem.plainSnippet) {
            val contentText= contentText(description)
            feedItem.wordCount= contentText.length
            feedItem.plainSnippet = contentText.take(100)
            context.modifyFlag=true
        }
        return chain.proceed(feed, feedItem)
    }
}